package org.turman.buobaobook.utils;

import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import org.turman.buobaobook.model.pojo.EmailProperties;

import java.util.Properties;

public class MailUtil {

    public static boolean sendMail(EmailProperties emailProperties, String to, String subject, String content) {
        Properties prop = new Properties();
        prop.put("mail.smtp.auth", emailProperties.isAuth());
        prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        prop.put("mail.smtp.socketFactory.fallback", "false");
        prop.put("mail.smtp.socketFactory.port", "465");
        prop.put("mail.smtp.host", emailProperties.getHost());
        prop.put("mail.smtp.port", "465");


        Session session = Session.getInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailProperties.getUser(), emailProperties.getCode());
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(emailProperties.getUser()));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);
            message.setContent(content, "text/html;charset=utf-8");
            Transport.send(message);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }
}
